﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using LuKou.Web.Core;

namespace LuKou.Web.UserAuth
{
    public class UserMembership : IMembership
    {
        public UserMembership()
        {
            this.User = new UserModel();
            Authority = new Authority();
            CookieString = string.Empty;
        }
        protected virtual string CookieName 
        {
            get { return WebConfig.PrefixKey + "UserCookie"; }
        }

        #region IMembership 成员
        public UserModel User { get; protected set; }

        public IAuthority Authority { get; protected set; }

        public string CookieString { get; protected set; }
        
        public virtual void Read()
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(CookieName);
            if (cookie == null)
            {
                User = new UserModel();
            }
            else
            {
                CookieString = cookie.Value;
                User = SecurityCookie.DecryptFromBase64(cookie.Value);
            }
            try
            {
                //Authority.Fill(User.Code);
            }
            catch (Exception e)
            {
                throw new Exception("无法将数据库中的权限数据转换为数据实体", e);
            }
        }

        public void Write(UserModel user)
        {
            Write(user, DateTime.MinValue);
        }

        public virtual void Write(UserModel user,DateTime expressTime)
        {
            User = user;

            HttpCookie cookie = new HttpCookie(CookieName);
            cookie.Value = SecurityCookie.EncryptToBase64(user);

            if (expressTime != DateTime.MaxValue && expressTime != DateTime.MinValue)
            {
                cookie.Expires = expressTime;
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public void Logout()
        {
            User = new UserModel();
            Write(User);
        }
        #endregion

        #region IDisposable 成员

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}
